package model;

import java.util.Iterator;
import java.util.LinkedList;

import model.exceptions.NoObjectivesException;
import model.exceptions.NoTreesException;
import model.interfaces.Node;
import model.interfaces.Objective;
import model.interfaces.Rule;
import model.interfaces.Session;

public class SequentialSession extends Session {
	
	private TreeIterator treeIterator = new TreeIterator();
	
	@Override
	public void verifyRules() throws NoObjectivesException, NoTreesException{
		
		super.verifyRules();
		
		for(Objective actual : objectiveList){
			this.treeIterator.setRoot(actual.getObjective());
			LinkedList<Rule> rulesList = this.getRulesList(actual);
			for(Object object : this.objects){
				boolean stop = false;
				Iterator<Rule> it = rulesList.iterator();
				Node nextAchievement = treeIterator.seekNextAchievement(actual,actual.getObjective());
				while((it.hasNext())&&(!stop)){
					this.doAddObject(object, it.next());
					//Recalculate next achievement
					nextAchievement = treeIterator.seekNextAchievement(actual, actual.getObjective());
					//quiero calcular el prox pero no adelantar otra vez el it
					//stop = treeIterator.isRuleValid(it.next(), actual, nextAchievement);
				}
				//Reset the rules after the first not verified
				this.treeIterator.cleanRules(rulesList, nextAchievement);
			}
			if(actual.isAchieved())
				actual.execute();
			this.clearObjective(rulesList);
		}
	}

	
}
